package com.allwees.core.dao.configuration.datapermission;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

/**
 * 为了被PermissionSqlProcessor处理SQL，故建立此类
 *
 * @author yangylsky
 * @since 2020-03-09
 */
@Slf4j
@Setter
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class PermissionPaginationInterceptor extends PaginationInterceptor {
    private PermissionSqlProcessor sqlProcessor;

    @Override
    protected void queryTotal(String sql, MappedStatement mappedStatement, BoundSql boundSql, IPage<?> page, Connection connection) {
        if (sqlProcessor != null && DataPermissionUtil.canProcessSql(mappedStatement.getId())) {
            sql = sqlProcessor.processSql(SqlCommandType.SELECT, sql);
        }
        super.queryTotal(sql, mappedStatement, boundSql, page, connection);
    }
}
